<template>
  <div class="zhouyi-container p-6 max-w-3xl mx-auto">
    <div class="mb-4">
      <h2 class="text-2xl font-semibold">周易算卦</h2>
      <p class="text-sm text-gray-600 mt-2">使用三枚铜钱法随机生成卦象，查看六爻结果并发送到解析页面进行 AI 解读。</p>
    </div>

    <div class="bg-white p-4 rounded shadow-sm">
      <div class="flex items-center gap-4 mb-4">
        <label class="inline-flex items-center"><input type="radio" v-model="method" value="three-coins" class="mr-2" /> 三枚铜钱法</label>
        <label class="inline-flex items-center"><input type="radio" v-model="method" value="random" class="mr-2" /> 随机（简化）</label>
      </div>

      <div class="mb-4">
        <button @click="generateHexagram" :disabled="loading" class="px-4 py-2 bg-indigo-600 text-white rounded">
          <span v-if="!loading">掷卦 / 生成卦象</span>
          <span v-else>生成中...</span>
        </button>
        <button v-if="hasHexagram" @click="sendToChat" class="ml-3 px-4 py-2 bg-green-600 text-white rounded">发送到解析</button>
      </div>

      <div v-if="hasHexagram" class="mt-4">
        <div class="mb-3 text-sm text-gray-700">说明：下为初爻（第1爻），上为上爻（第6爻）。值说明：6=老阴(变爻)，7=少阳，8=少阴，9=老阳(变爻)</div>

        <div class="space-y-2">
          <div v-for="(line, idx) in linesDisplay" :key="idx" class="flex items-center justify-between bg-gray-50 p-2 rounded">
            <div class="text-sm text-gray-700">第 {{ idx + 1 }} 爻 (从下往上) </div>
            <div class="text-right">
              <div class="font-mono">{{ line.symbol }}  ({{ line.value }})</div>
              <div class="text-xs text-gray-500">{{ line.coins }}</div>
            </div>
          </div>
        </div>

        <div class="mt-4 p-3 bg-white border rounded">
          <div class="text-sm text-gray-700">二进制（阳=1 阴=0）从下到上： <span class="font-mono">{{ binaryString }}</span></div>
          <div class="mt-2 text-sm text-gray-700">简单卦信息（下卦 / 上卦）: <span class="font-mono">{{ lowerTrigram }} / {{ upperTrigram }}</span></div>
        </div>
      </div>

      <div v-else class="text-sm text-gray-500 mt-2">尚未生成卦象，请点击“掷卦 / 生成卦象”。</div>
    </div>

    <div class="mt-6 text-sm text-gray-500">
      <p>资源参考：<a class="text-blue-600 underline" href="https://github.com/zombielive/ZhouYi" target="_blank">ZhouYi · GitHub</a>（仅作参考；本页面使用三枚铜钱的简单算法生成卦象并将数据发送给聊天解析）。</p>
    </div>
  </div>
</template>

<script setup>
definePageMeta({ middleware: 'admin-access' })
</script>

<script>
export default {
  name: 'ZhouyiPage',
  data() {
    return {
      method: 'three-coins',
      loading: false,
      rawLines: null, // array of 6 numbers (6/7/8/9) bottom->top
      massage: null, // object returned from zhouYi()
      guaData: null, // matched entry from data.js
      scriptsLoaded: false
    }
  },
  computed: {
    hasHexagram() {
      return Array.isArray(this.rawLines) && this.rawLines.length === 6
    },
    linesDisplay() {
      if (!this.hasHexagram) return []
      // Display from bottom (index 0) to top (index 5)
      return this.rawLines.map((v, i) => ({
        value: v,
        symbol: this.lineSymbol(v),
        coins: this.coinsForValue(v)
      }))
    },
    binaryString() {
      if (!this.hasHexagram) return ''
      // 阳为1：7和9 为阳，阴为0：6和8 为阴； show from bottom->top
      return this.rawLines.map(v => (v === 7 || v === 9 ? '1' : '0')).join('')
    },
    lowerTrigram() {
      if (!this.hasHexagram) return ''
      const lower = this.rawLines.slice(0,3) // bottom 3
      return this.trigramName(lower)
    },
    upperTrigram() {
      if (!this.hasHexagram) return ''
      const upper = this.rawLines.slice(3,6) // top 3
      return this.trigramName(upper)
    }
  },
  methods: {
    // Dynamically inject a script and return a Promise
    loadScript(src) {
      return new Promise((resolve, reject) => {
        // If already loaded (script created earlier), resolve when window has expected globals
        const existing = Array.from(document.getElementsByTagName('script')).find(s => s.src && s.src.indexOf(src) !== -1)
        if (existing) {
          existing.addEventListener('load', () => resolve())
          existing.addEventListener('error', () => reject(new Error('Script load error')))
          // If already completed loading, resolve immediately
          if (existing.readyState === 'complete' || existing.readyState === 'loaded') resolve()
          return
        }
        const s = document.createElement('script')
        s.src = src
        s.async = true
        s.onload = () => resolve()
        s.onerror = () => reject(new Error('Script load error: ' + src))
        document.head.appendChild(s)
      })
    },

    // Ensure both zhouyi and data are available on window
    async loadZhouyiScripts() {
      if (this.scriptsLoaded && window.zhouYi && window.data) return
      try {
        // scripts are in `public/scripts/` and served from `/scripts/`
        await this.loadScript('/scripts/zhouyi.js')
        await this.loadScript('/scripts/data.js')
        // small delay to ensure globals are set
        await new Promise(r => setTimeout(r, 10))
        this.scriptsLoaded = true
      } catch (e) {
        console.error('加载周易脚本失败', e)
        throw e
      }
    },
    // Map line value to display symbol
    lineSymbol(v) {
      // Yang: —— (实线), Yin: -- -- (断线); older changing lines marked with ○/●
      if (v === 6) return '-- -- ○' // old yin
      if (v === 8) return '-- --'   // young yin
      if (v === 7) return '——'      // young yang
      if (v === 9) return '—— ●'    // old yang
      return String(v)
    },
    coinsForValue(v) {
      // reverse map approximate coin results: heads=3 tails=2 ; sums 6/7/8/9
      // We simulate to show example coins; here just return example pattern
      if (v === 6) return '2,2,2'
      if (v === 7) return '3,2,2'
      if (v === 8) return '3,3,2'
      if (v === 9) return '3,3,3'
      return ''
    },
    // Determine trigram name based on three lines array [bottom,mid,top]
    trigramName(lines3) {
      // Map binary code (from bottom->top) to common trigrams
      // binary bit: yang=1, yin=0
      const bits = lines3.map(v => (v === 7 || v === 9 ? '1' : '0')).join('')
      // Map according to order: 000=坤,001=兑,010=离,011=震,100=巽,101=坎,110=艮,111=乾
      const map = {
        '000': '坤',
        '001': '兑',
        '010': '离',
        '011': '震',
        '100': '巽',
        '101': '坎',
        '110': '艮',
        '111': '乾'
      }
      return map[bits] || bits
    },
    generateHexagram() {
      this.loading = true
      this.rawLines = null
      this.massage = null
      this.guaData = null
      // small delay to keep UX similar
      setTimeout(async () => {
        try {
          await this.loadZhouyiScripts()
          // Build sixYao array to pass into zhouYi (values 6/7/8/9)
          const six = []
          if (this.method === 'three-coins') {
            for (let i = 0; i < 6; i++) {
              const c1 = Math.random() < 0.5 ? 3 : 2
              const c2 = Math.random() < 0.5 ? 3 : 2
              const c3 = Math.random() < 0.5 ? 3 : 2
              six.push(c1 + c2 + c3)
            }
          } else {
            const choices = [6,7,8,9]
            for (let i = 0; i < 6; i++) six.push(choices[Math.floor(Math.random()*4)])
          }
          // Call the global function from zhouyi.js
          const res = window.zhouYi ? window.zhouYi(six) : null
          if (!res) throw new Error('zhouYi 函数不可用')
          this.massage = res
          this.rawLines = res.benGua
          // try to find matching gua data
          if (window.data && Array.isArray(window.data)) {
            const idx = window.data.findIndex(d => d.yinYang && d.yinYang.toString() === res.drawBenGua.toString())
            if (idx !== -1) this.guaData = window.data[idx]
          }
        } catch (e) {
          console.error(e)
          alert('生成卦象失败：' + (e && e.message ? e.message : '未知错误'))
        } finally {
          this.loading = false
        }
      }, 200)
    },
    sendToChat() {
      if (!this.hasHexagram) return
      const prompt = this.buildPrompt()
      import('@/lin/util/data-transfer').then(({ saveData, generateUniqueId }) => {
        const id = generateUniqueId()
        const ok = saveData(id, prompt)
        if (ok) {
          window.open(`/ai-tools/chat?data_id=${id}`)
        } else {
          alert('保存数据失败')
        }
      }).catch(e => {
        console.error(e)
        try {
          const encoded = encodeURIComponent(prompt)
          window.open(`/ai-tools/chat?user_input=${encoded}`)
        } catch (err) {
          alert('跳转到聊天页失败')
        }
      })
    },
    buildPrompt() {
      // Build a human-readable description of the hexagram for AI parsing
      const linesText = (this.rawLines || []).map((v, i) => `第${i+1}爻（从下往上）：${v}；${this.lineSymbol(v)}`).join('\n')
      // Use massage.content if available (it's HTML in zhouyi.js), but also include structured info
      let guaInfo = ''
      if (this.guaData) {
        guaInfo += `卦名：${this.guaData.guaName}\n卦辞：${this.guaData.guaCi || ''}\n` 
        if (Array.isArray(this.guaData.yaoCi)) {
          guaInfo += `爻辞（共${this.guaData.yaoCi.length}爻）：\n`
          this.guaData.yaoCi.forEach((yc, idx) => {
            guaInfo += `第${idx+1}爻：${yc}\n`
          })
        }
      }
      const prompt = `请作为《周易》与卦象解析专家，解析下面的卦：\n生成方法：${this.method === 'three-coins' ? '三枚铜钱法' : '随机简化方法'}\n${linesText}\n二进制(下→上)：${this.binaryString}\n下卦：${this.lowerTrigram}，上卦：${this.upperTrigram}。\n${guaInfo}\n（注意：以下是 zhouyi.js 合成的解析片段，可用于参考）\n${this.massage && this.massage.content ? this.massage.content : ''}\n\n请给出：卦名、卦辞、爻辞（如有变爻则说明变爻含义）、总体解读、给出日常生活建议（简明扼要）。`
      return prompt
    }
  }
}
</script>

<style scoped>
.zhouyi-container { padding-bottom: 30px }
.font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, 'Roboto Mono', 'Helvetica Neue', monospace }
</style>
